<route lang="json5" type="page">
{
  layout: 'tabbar',
  needLogin: true,
  style: {
    navigationBarTitleText: '水表管理',
  },
}
</route>

<script setup lang="ts">
import dayjs from 'dayjs'
import { computed, nextTick, ref } from 'vue'

// 当前选中的水表
const selectedMeter = ref('501水表（预付）')

// 日历相关
const currentDate = ref(Date.now()) // 改为时间戳格式
const calendarKey = ref(0) // 用于强制重新渲染日历组件
const calendarRef = ref() // 日历组件引用
const selectedDates = ref([]) // 存储选择的日期范围
const selectedDateRange = ref([]) // 存储选择的日期范围
const minDate = ref(dayjs().subtract(1, 'year').toDate().getTime())

// 水表选项
const meterOptions = [
  '501水表（预付）',
  '502水表（预付）',
  '503水表（预付）',
]

// 模拟水表数据
const waterData = ref([
  {
    id: 1,
    time: '1月10日',
    dailyUsage: 0.58,
    cumulativeUsage: 50.0,
    status: '表内扣款',
    statusType: 'normal',
  },
  {
    id: 2,
    time: '1月11日',
    dailyUsage: 0.38,
    cumulativeUsage: 0,
    status: '余额扣款',
    statusType: 'warning',
  },
  {
    id: 3,
    time: '1月12日',
    dailyUsage: 0.28,
    cumulativeUsage: 32.8,
    status: '表内扣款',
    statusType: 'normal',
  },
  {
    id: 4,
    time: '1月13日',
    dailyUsage: 0.38,
    cumulativeUsage: 33.8,
    status: '表内扣款',
    statusType: 'normal',
  },
  {
    id: 5,
    time: '1月14日',
    dailyUsage: 20.0,
    cumulativeUsage: 33.8,
    status: '表内扣款',
    statusType: 'normal',
  },
  {
    id: 6,
    time: '1月15日',
    dailyUsage: 0.57,
    cumulativeUsage: 33.8,
    status: '表内扣款',
    statusType: 'normal',
  },
  {
    id: 7,
    time: '1月16日',
    dailyUsage: 0.48,
    cumulativeUsage: 33.8,
    status: '表内扣款',
    statusType: 'normal',
  },
  {
    id: 8,
    time: '1月17日',
    dailyUsage: 0.58,
    cumulativeUsage: -1.0,
    status: '余额扣款不足',
    statusType: 'error',
  },
  {
    id: 9,
    time: '1月18日',
    dailyUsage: 0.38,
    cumulativeUsage: 0,
    status: '余额扣款',
    statusType: 'warning',
  },
  {
    id: 10,
    time: '1月19日',
    dailyUsage: 0.48,
    cumulativeUsage: 33.8,
    status: '表内扣款',
    statusType: 'normal',
  },
])

// 格式化日期显示 - 始终显示当前日历面板的年月
const formattedDate = computed(() => {
  const date = new Date(currentDate.value)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
  return `${monthNames[month - 1]} ${year}`
})

// 日历格式化函数
function calendarFormatter(day: any) {
  const date = new Date(day.date)
  const dayOfMonth = date.getDate()

  // 标记有数据的日期 - 显示小圆点
  if (dayOfMonth === 10 || dayOfMonth === 15 || dayOfMonth === 12 || dayOfMonth === 16 || dayOfMonth === 29) {
    day.bottomInfo = '•'
  }

  // 注释掉选中日期的底部信息
  // if (day.type === 'selected') {
  //   day.bottomInfo = '已选择'
  // }

  return day
}

// 获取状态颜色
function getStatusColor(statusType: string) {
  switch (statusType) {
    case 'normal':
      return 'text-green-600'
    case 'warning':
      return 'text-orange-500'
    case 'error':
      return 'text-red-500'
    default:
      return 'text-gray-600'
  }
}

// 切换水表
function changeMeter() {
  uni.showActionSheet({
    itemList: meterOptions,
    success: (res) => {
      selectedMeter.value = meterOptions[res.tapIndex]
      // 重新加载数据
      loadWaterData()
    },
  })
}

// 日历日期变化事件
function onCalendarChange(event: any) {
  console.log('选中日期：', event.value)
  if (event.value && event.value.length >= 2) {
    // 保存选择的日期范围
    selectedDateRange.value = event.value
    // 重新加载数据
    loadWaterData()
  }
}

// 上个月
async function prevMonth() {
  const date = new Date(currentDate.value)
  date.setMonth(date.getMonth() - 1)
  currentDate.value = date.getTime()
  calendarKey.value++ // 强制重新渲染日历
  await nextTick() // 等待DOM更新

  // 等待一小段时间确保组件完全渲染
  setTimeout(() => {
    if (calendarRef.value) {
      calendarRef.value.scrollIntoView()
    }
  }, 100)

  loadWaterData()
}

// 下个月
async function nextMonth() {
  const date = new Date(currentDate.value)
  date.setMonth(date.getMonth() + 1)
  currentDate.value = date.getTime()
  calendarKey.value++ // 强制重新渲染日历
  await nextTick() // 等待DOM更新

  // 等待一小段时间确保组件完全渲染
  setTimeout(() => {
    if (calendarRef.value) {
      calendarRef.value.scrollIntoView()
    }
  }, 100)

  loadWaterData()
}

// 加载水表数据
function loadWaterData() {
  uni.showLoading({ title: '加载中...' })

  // 模拟API请求
  setTimeout(() => {
    uni.hideLoading()
    uni.showToast({ title: '数据已更新', icon: 'success' })
  }, 1000)
}

// 下拉刷新
function onRefresh() {
  loadWaterData()
}
</script>

<template>
  <view class="water-page min-h-screen bg-gray-50">
    <!-- 水表选择器 -->
    <view class="bg-blue-400 px-4 py-3">
      <view class="flex items-center justify-between" @click="changeMeter">
        <view class="flex items-center text-white">
          <wd-icon name="arrow-down" size="16px" color="#fff" class="mr-2" />
          <text class="ml-1 text-base font-medium">
            {{ selectedMeter }}
          </text>
        </view>
        <text class="text-white font-bold">
          数据查询
        </text>
      </view>
    </view>

    <!-- 日历选择器 -->
    <view class="mx-3 mt-3 overflow-hidden rounded-lg bg-white">
      <!-- <view class="border-b border-gray-100 px-4 py-4">
        <view class="flex items-center justify-between">
          <text class="text-lg text-gray-800 font-medium">
            七月 2025
          </text>
          <view class="flex items-center">
            <view class="p-2" @click="prevMonth">
              <wd-icon name="arrow-left" size="18px" color="#666" />
            </view>
            <view class="ml-2 p-2" @click="nextMonth">
              <wd-icon name="arrow-right" size="18px" color="#666" />
            </view>
          </view>
        </view>
      </view> -->

      <!-- 使用 wd-calendar-view 日历组件 -->
      <view class="px-4 py-3">
        <wd-calendar-view
          ref="calendarRef" :key="calendarKey" v-model="currentDate" type="daterange"
          :formatter="calendarFormatter" :panel-height="250" :max-date="new Date().getTime()"
          allow-same-day
          :min-date="minDate"
          @change="onCalendarChange"
        />
      </view>
    </view>

    <!-- 水表数据表格 -->
    <view class="mx-3 mb-6 mt-3">
      <wd-table :data="waterData" custom-class="water-table" :stripe="false" :border="false">
        <wd-table-col prop="time" label="时间" width="25%" align="center" />
        <wd-table-col prop="dailyUsage" label="日用水量" width="25%" align="center" />
        <wd-table-col prop="cumulativeUsage" label="剩余水量" width="25%" align="center" />
        <wd-table-col prop="status" label="扣款途径" width="25%" align="center">
          <template #value="{ row }">
            <text class="text-xs" :class="getStatusColor(row.statusType)">
              {{ row.status }}
            </text>
          </template>
        </wd-table-col>
      </wd-table>
    </view>
  </view>
</template>

<style scoped>
.water-page {
  padding-bottom: env(safe-area-inset-bottom);
}

:deep(.water-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  table-layout: fixed;
}

:deep(.water-table .wd-table__header) {
  background-color: #f8fafc;
}

:deep(.water-table .wd-table__cell) {
  text-align: center;
  padding: 12px 4px;
  font-size: 12px;
  word-wrap: break-word;
  white-space: normal;
  min-width: 0;
}

:deep(.water-table .wd-table__row:nth-child(even)) {
  background-color: #fafafa;
}

:deep(.water-table .wd-table__row:hover) {
  background-color: #f0f9ff;
}

/* 自定义日历组件样式 */
:deep(.wd-calendar-view) {
  background: transparent;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

:deep(.wd-calendar-view .wd-calendar-view__header) {
  display: none;
  /* 隐藏默认的面板标题，我们使用自己的 */
}

:deep(.wd-calendar-view .wd-calendar-view__body) {
  padding: 0;
}

:deep(.wd-calendar-view .wd-calendar-view__week) {
  color: #666;
  font-size: 14px;
  font-weight: 400;
  padding: 8px 0;
}

:deep(.wd-calendar-view .wd-calendar-view__cell) {
  margin: 1px;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 400;
  color: #333;
  position: relative;
}

:deep(.wd-calendar-view .wd-calendar-view__cell--selected) {
  background-color: #4285f4 !important;
  color: white !important;
  font-weight: 500;
}

:deep(.wd-calendar-view .wd-calendar-view__cell--current) {
  color: #4285f4;
  font-weight: 500;
}

:deep(.wd-calendar-view .wd-calendar-view__cell--other-month) {
  color: #ccc;
}

:deep(.wd-calendar-view .wd-calendar-view__cell--disabled) {
  color: #ddd;
}

:deep(.wd-calendar-view .wd-calendar-view__info) {
  font-size: 12px;
  line-height: 1;
}

:deep(.wd-calendar-view .wd-calendar-view__top-info) {
  color: #f59e0b;
  margin-bottom: 2px;
}

:deep(.wd-calendar-view .wd-calendar-view__bottom-info) {
  color: #4285f4;
  font-size: 8px;
  position: absolute;
  bottom: 2px;
  left: 50%;
  transform: translateX(-50%);
}
</style>
